import java.util.Comparator;
import java.util.PriorityQueue;

public class TopK {
    public int[] topMaxK(int[] array,int k) {
        PriorityQueue<Integer> p = new PriorityQueue<>();
        int[] ret =new int[k];
        for (int i = 0; i < k; i++) {
            p.offer(array[i]);
        }
        for (int i = k; i < array.length; i++) {
            int a = array[i];
            int b = p.peek();
            if (a > b) {
                p.poll();
                p.offer(a);
            }
        }
        for (int i = 0; i < k; i++) {
            ret[i] = p.poll();
        }
        return ret;
    }

    class IntCmp implements Comparator<Integer> {

        @Override
        public int compare(Integer o1, Integer o2) {
            return o2.compareTo(o1);
        }
    }

    public int[] smallestK(int[] array, int k) {
        int[] ret = new int[k];
        if(array == null || k <= 0) {
            return ret;
        }
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new IntCmp());
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(array[i]);
        }

        for (int i = k; i < array.length; i++) {
            int top = priorityQueue.peek();
            if(array[i] < top) {
                priorityQueue.poll();
                priorityQueue.offer(array[i]);
            }
        }
        for (int i = 0; i < k; i++) {
            ret[i] = priorityQueue.poll();
        }
        return ret;
    }
}
